package com.teste.util;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.hibernate.SessionFactory;


public class HibernateUtilConexaoFilter implements Filter {

	private SessionFactory sf;		
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		try{			
			System.out.println("Iniciando Filter");
			this.sf.getCurrentSession().beginTransaction();
			System.out.println("Begin Transaction");
			chain.doFilter(servletRequest, servletResponse);
			System.out.println("doFilter executado");
			this.sf.getCurrentSession().getTransaction().commit();
			System.out.println("Commitado");
			this.sf.getCurrentSession().close();
			System.out.println("Conexao Fechada");
		}catch (Throwable e){
			try{
				if (this.sf.getCurrentSession().getTransaction().isActive()){					
					System.out.println("Erro, rollback" + e);
					e.printStackTrace();
					this.sf.getCurrentSession().getTransaction().rollback();				
				}
			} catch (Throwable t){				
				t.printStackTrace();
			}
			throw new ServletException();			
		}
		
	}

	@Override
	public void init(FilterConfig conf) throws ServletException {
		this.sf = HibernateUtil.getSessionFactory();		
	}

}
